package com.des1gn.config;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.stereotype.Component;

@Component
public class NettyHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 消息读取
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        //回复消息
        sendInfo(channelHandlerContext,"");
    }

    private void sendInfo(ChannelHandlerContext ctx , String info) {
        ctx.writeAndFlush(info);
        ctx.flush();
    }

    /**
     * 心跳检测
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            switch (event.state()){
                case READER_IDLE:
                    //读空闲
                    break;
                case WRITER_IDLE:
                    //写空闲
                    break;
                case ALL_IDLE:
                    //读写空闲
                    break;
                default:
                    //无法确认状态
                    break;
            }
        }
    }



    /**
     * 通道连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    /**
     * 异常断连
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 离线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
}
